import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
class TransportationTrajectory extends StatefulWidget {
  const TransportationTrajectory({super.key});

  @override
  State<TransportationTrajectory> createState() => _TransportationTrajectoryState();
}

class _TransportationTrajectoryState extends State<TransportationTrajectory> {
  late BMFMapController myMapController;
  late Size screenSize=MediaQuery.of(context).size;

  late BMFTraceOverlay _traceOverlay;
  late bool _addState = false;
  late String _btnText = "删除";

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;

    /// 设置traceOverlay动画开始回调
    myMapController.setTraceOverlayAnimationDidStartCallback((traceOverlay) {
      print(
          'TraceOverlayAnimationDidStartCallback: traceOverlay = ${traceOverlay.id}');
    });

    /// 设置traceOverlay动画进度回调
    myMapController.setTraceOverlayAnimationRunningProgressCallback(
            (traceOverlay, progress) {
          print(
              'TraceOverlayAnimationRunningProgressCallback: traceOverlay = ${traceOverlay.id} progress = ${progress}}');
        });

    /// 设置traceOverlay动画结束回调
    myMapController
        .setTraceOverlayAnimationDidEndCallback((traceOverlay, flag) {
      print(
          'TraceOverlayAnimationDidEndCallback: traceOverlay = ${traceOverlay.id} flag = ${flag}}');
    });

    myMapController
        .setTraceOverlayAnimationUpdatePositionCallback((coordinate) {
      print(
          'setTraceOverlayAnimationUpdatePositionCallback: coordinate = ${coordinate.toMap()}}');
    });

    /// 添加traceOverlay
    _addTraceOverlay();
  }
  @override
  Widget build(BuildContext context) {
    // final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("运输轨迹",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: Stack(
        children: [
          generateMap(),
          generateControlList(),
          generateControlCar(),
        ],
      ),
    );
  }
  Widget generateControlList() {

    return Container(
      margin: EdgeInsets.only(top: 300.h,left: 10.w,right: 10.w,bottom: 40.h),
      width: screenSize.width,
      height: screenSize.height -300.h,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child:Column(
        children: [
            Container(
              padding: EdgeInsets.only(left: 11.w,right: 9.w),
              width: screenSize.width-20.w,
              height: 40.h,
              decoration: BoxDecoration(
                  color: Color.fromRGBO(251, 236, 228, 1),
                  borderRadius: BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10) )),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                    Text("查看货车即时位置",style: TextStyle(color: Colors.black),),
                    GestureDetector(
                      child: Container(
                        padding: EdgeInsets.only(top: 4.h,bottom: 4.h,left: 6.w,right: 6.w),
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: MyColors.themeColor, // 边框颜色
                            width: 1.0, // 边框宽度
                          ),
                          borderRadius: BorderRadius.circular(30.0), // 可选：边框圆角
                        ),
                        child: Row(
                          children: [
                            Text("精准定位",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                            Icon(Icons.gps_fixed,color: MyColors.themeColor,size: 18,),
                          ],
                        ), // 您的子部件
                      ),
                      onTap: (){

                      },
                    ),
                ],
              ),
            ),
          Container(
            padding: EdgeInsets.only(top: 12.h),
            height: 190.h,
            child:  ListView.builder(
                itemCount:5,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    padding: EdgeInsets.only(left: 8.w,right: 8.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Column(
                        children: [
                          Text("05-29",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                          Text("16:07",style: TextStyle(color: Colors.black,fontSize: 12.sp),),
                        ],
                        ),
                        Column(
                          children: [
                            if(index==0)
                              SizedBox(height: 15.h,),
                            if(index!=0)
                            Image.asset("lib/Images/OrderList/垂直虚线.png",height: 20.h,),
                            index==0?Icon(Icons.circle,color: MyColors.themeColor,size: 14,):Icon(Icons.circle,color: MyColors.hintColor,size: 14,),
                            if(index!=4)
                            Image.asset("lib/Images/OrderList/垂直虚线.png",height: 20.h,),
                            if(index==4)
                              SizedBox(height: 15.h,),
                          ],
                        ),
                        Container(
                          width: 180.w,
                          child: Text("江苏省苏州市吴中区科营路2号中新生态大厦",style: TextStyle(color: index==0?Colors.black:MyColors.authTipColor,fontSize: 13.sp),),
                        ),
                        Text("(手机定位)",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                      ],
                    ),
                  );
                }
                ),
          ),
          Divider(height: 10.h,color: MyColors.backgreyColor,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(),
              GestureDetector(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Icon(Icons.open_in_new),
                    Text("分享轨迹",style: TextStyle(fontSize: 14.sp,color: Colors.black),),
                  ],
                ),
                onTap: (){

                },
              ),
              Container(height: 20.h,width: 1.w,color: MyColors.backgreyColor,),
              GestureDetector(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Image.asset("lib/Images/OrderList/电话联系icon.png",width: 20.w,height: 20.h,),
                    Text("联系司机",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor),),
                  ],
                ),
                onTap: (){

                },
              ),
              SizedBox(),
            ],
          )
        ],
      ),
    );
  }
  Widget generateControlCar() {
    return Container(
      padding: EdgeInsets.only(left: 8.w,right: 8.w,top: 5.h,bottom: 5.h),
      margin: EdgeInsets.only(bottom: 310.h,left: 10.w,right: 10.w,top: 260.h),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      width: 130.w,
      height: 40.h,
      child: Row(
        children: [
          Icon(Icons.fmd_good,color: MyColors.themeColor,),
          Text("苏E12345",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
        ],
      ),
    );
  }

  /// 创建地图
  Container generateMap() {
    return Container(
      height: screenSize.height,
      width: screenSize.width,
      child: BMFMapWidget(
        onBMFMapCreated: (controller) {
          onBMFMapCreated(controller);
        },
        mapOptions: BMFMapOptions(
            center: BMFCoordinate(40.048997, 116.309648), zoomLevel: 16),
      ),
    );
  }

  Future<void> _addTraceOverlay() async {
    /// 读取动态轨迹点
    String coordinateStrings =
    await rootBundle.loadString('lib/AppConfig/trace_path.txt');

    /// string -> list
    List<String> coordinateStringList = coordinateStrings.split(',');

    /// 动态轨迹点
    List<BMFCoordinate> coords = [];

    /// 渐变色
    List<Color> colors = [];
    for (var i = 0; i < coordinateStringList.length; i += 2) {
      BMFCoordinate coordinate = BMFCoordinate(
          double.parse(coordinateStringList[i + 1]),
          double.parse(coordinateStringList[i]));
      coords.add(coordinate);
      colors.add(MyColors.themeColor);
      // if (i < 50) {
      //   colors.add(Color.fromARGB(255, 255, 0, 0));
      // } else if (i >= 50 && i < 100) {
      //   colors.add(Color.fromARGB(255, 0, 255, 0));
      // } else if (i >= 100 && i < 150) {
      //   colors.add(Color.fromARGB(255, 0, 0, 255));
      // } else {
      //   colors.add(Color.fromARGB(255, 123, 11, 13));
      // }
    }

    /// 构造动态轨迹动画参数
    BMFTraceOverlayAnimateOption traceOverlayAnimateOption =
    BMFTraceOverlayAnimateOption(
      animate: true,
      delay: 0.0,
      duration: 8,
      fromValue: 0.0,
      toValue: 1.0,
      easingCurve: BMFTraceOverlayAnimationEasingCurve.Linear,
      trackMove: false,
      isPointMove: true,
      isRotateWhenTrack: true,
      // icon: "resoures/driving.png",
      modelOption: BMFTrace3DModelOption(
          modelName: "scenes",
          modelPath: 'resoures/Model3D',
          yawAxis: BMFTraceOverlay3DModelYawAxis.YawAxisX,
          scale: 3.0,
          zoomFixed: true,
          animationIsEnable: true,
          animationIndex: 1,
          type: BMF3DModelType.BMF3DModelTypeGLTF),
    );

    /// 构造动态轨迹
    _traceOverlay = BMFTraceOverlay(
        coordinates: coords,
        traceOverlayAnimateOption: traceOverlayAnimateOption,
        isTrackBloom: true,
        isGradientColor: true,
        bloomSpeed: 5.0,
        isCornerSmooth: false,
        strokeColors: colors);
    await myMapController.addTraceOverlay(_traceOverlay);
  }

  void _removeTraceOverlay() {
    myMapController.removeTraceOverlay(_traceOverlay.id);
  }

  void onBtnPress() {
    if (_addState) {
      _addTraceOverlay();
    } else {
      _removeTraceOverlay();
    }
    _addState = !_addState;
    setState(() {
      _btnText = _addState == true ? "添加" : "删除";
    });
  }
}

